import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import express from 'express'
import { createServer as createViteServer } from 'vite'
import 'dotenv/config'
import { generateJwt } from './src/components/Tiptap/tiptap-jwt/generator.js';


const __dirname = path.dirname(fileURLToPath(import.meta.url))

async function createServer() {
  const app = express()

  // Middleware to parse JSON bodies
  app.use(express.json());
  
  // JWT generation endpoint
  app.post('/api/collaboration/token', (req, res) => {
    try {
      const { sub, allowedDocumentNames, readonlyDocumentNames } = req.body;
      if (!sub || !allowedDocumentNames) {
        return res.status(400).json({ error: 'Missing required fields: sub and allowedDocumentNames.' });
      }
      const token = generateJwt({ sub, allowedDocumentNames, readonlyDocumentNames });
      res.status(200).json({ token });
    } catch (error) {
      console.error('JWT Generation Error:', error);
      res.status(500).json({ error: 'Failed to generate token.' });
    }
  });
  
  // 创建 Vite 服务器用于开发
  const vite = await createViteServer({
    server: { middlewareMode: true },
    appType: 'custom'
  })
  
  // 使用 Vite 的中间件，但不包括 ssrLoadModule
  app.use(vite.middlewares)
  
  // SSR路由处理 - 处理根路径、登录和注册页
  app.get(['/', '/login', '/register'], async (req, res) => {
    const url = req.originalUrl
    
    try {
      // 1. 读取 index.html
      let template = fs.readFileSync(
        path.resolve(__dirname, 'index.html'),
        'utf-8'
      )
      
      // 2. 应用 Vite HTML 转换
      template = await vite.transformIndexHtml(url, template)
      
      // 3. 加载服务器入口
      const { render } = await vite.ssrLoadModule('/src/entry-server.jsx')
      
      // 4. 渲染应用的 HTML
      const renderResult = render(url)
      const appHtml = renderResult.html
      const styles = renderResult.styles
      
      // 5. 注入样式到模板头部
      let html = template.replace('<!--ssr-outlet-->', appHtml)
      
      // 6. 注入Ant Design样式和缓存信息
      if (styles) {
        html = html.replace(
          '<head>',
          `<head>
            <style data-ant-cssinjs-cache-path="server">${styles}</style>
            <style data-ssr-critical-css>
              /* SSR Critical CSS - 确保登录和注册页面样式一致性 */
              .ant-card.index-module__loginCard___eo-op {
                background-color: rgba(247, 247, 247) !important;
                width: 400px !important;
                border-radius: 10px !important;
                padding: 20px !important;
                z-index: 99 !important;
                box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03), 0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px 0 rgba(0, 0, 0, 0.02) !important;
                border: 1px solid rgba(0, 0, 0, 0.06) !important;
                position: relative !important;
              }
              .index-module__login___3O--t {
                display: flex !important;
                justify-content: center !important;
                align-items: center !important;
                height: 100vh !important;
                background: transparent !important;
                position: relative !important;
              }
              .index-module__logo___NU6bz {
                width: 100% !important;
                height: 55px !important;
                display: flex !important;
                justify-content: center !important;
                align-items: center !important;
                font-size: 22px !important;
                z-index: 99 !important;
                margin-bottom: 24px !important;
                font-weight: 600 !important;
                color: rgba(0, 0, 0, 0.85) !important;
                text-align: center !important;
              }
              /* 确保表单样式一致 */
              .ant-form-item {
                margin-bottom: 16px !important;
              }
              .ant-btn-block {
                width: 100% !important;
              }
              .ant-card-body {
                padding: 24px !important;
              }
              /* 确保输入框样式 */
              .ant-input-affix-wrapper.ant-input-affix-wrapper-lg {
                padding: 7px 11px !important;
                font-size: 16px !important;
                line-height: 1.5 !important;
                border-radius: 8px !important;
              }
              /* 确保按钮样式 */
              .ant-btn.ant-btn-primary.ant-btn-lg {
                height: 40px !important;
                padding: 7px 15px !important;
                font-size: 16px !important;
                line-height: 1.5 !important;
                border-radius: 8px !important;
              }
              /* 确保背景组件样式 */
              [style*="position:fixed"][style*="background-color:white"] {
                position: fixed !important;
                top: 0 !important;
                left: 0 !important;
                width: 100% !important;
                height: 100% !important;
                background-color: white !important;
                z-index: -1 !important;
              }
              /* 防止样式闪烁 */
              body {
                margin: 0 !important;
                padding: 0 !important;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif !important;
              }
              #root {
                height: 100vh !important;
                width: 100vw !important;
              }
            </style>
            <script>window.__ANTD_STYLE_CACHE__ = null;</script>`
        )
      }
      
              // 7. 返回渲染的 HTML
      res.status(200).set({ 'Content-Type': 'text/html' }).send(html)
    } catch (e) {
      vite && vite.ssrFixStacktrace(e)
      console.error('SSR Error:', e)
      res.status(500).send('Internal Server Error')
    }
  })
  
  // 其他路由使用客户端渲染
  app.get('*', async (req, res) => {
    try {
      let template = fs.readFileSync(
        path.resolve(__dirname, 'index.html'),
        'utf-8'
      )
      template = await vite.transformIndexHtml(req.originalUrl, template)
      
      // 客户端渲染，返回空的root div
      const html = template.replace('<!--ssr-outlet-->', '')
      res.status(200).set({ 'Content-Type': 'text/html' }).send(html)
    } catch (e) {
      console.error('CSR Error:', e)
      res.status(500).send('Internal Server Error')
    }
  })
  
  const port = 5173
  app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`)
    console.log('SSR enabled for: /login, /register')
    console.log('CSR for all other routes')
  })
}

createServer().catch(console.error)